package com.mall.order.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
@Component
@Slf4j
public class Producer {

    private final static String addr = "localhost:9876";
    DefaultMQProducer producer;

    // 发消息
    @PostConstruct
    public void init(){
        // 构建消息生产者
        producer = new DefaultMQProducer("producer_group");

        //设置注册中心
        producer.setNamesrvAddr(addr);

        // 启动消息生产者
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }


    }

    public void checkOrder(String orderId){
        // 创建消息对象
        Message message = new Message();

        message.setTopic("checkOrder");
        message.setBody(orderId.getBytes(Charset.forName("utf-8")));


        // 延迟级别 延迟级别从1开始 ，5s => 2       10s => 3
//        1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h

        message.setDelayTimeLevel(7);

        // 发送消息
        try {
            SendResult sendResult = producer.send(message);
            System.out.println("sendResult:" + sendResult);

            SendStatus sendStatus = sendResult.getSendStatus();

            if (SendStatus.SEND_OK.equals(sendStatus)) {

                System.out.println("消息发送成功！！！ time:" + System.currentTimeMillis());
                log.info("发送成功");
            }

        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
